import { defineStore } from 'pinia'
import request from '@/utils/request'
import { IAxsRes } from '@/types/data'
import { UserType } from '@/types/user'
import { setProfile, getProfile } from '@/utils/storage'
import router from '@/router'

export default defineStore('user', {
  state: () => {
    return {
      profile: getProfile() as UserType
    }
  },
  actions: {
    // 账号登录
    async accountLogin(password: string, account: string) {
      // axios.post/get本身就是一个泛型
      // 用来约束res.data
      // res.data code/msg/result
      // 我们又封装了一个泛型接口
      const res = await request.post<IAxsRes<UserType>>('/login', {
        password,
        account
      })
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 发送验证码
    async getCode(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile
        }
      })
    },
    // 短信登录
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<IAxsRes<UserType>>('/login/code', {
        mobile,
        code
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 三方QQ登录
    async qqLogin(openId: string) {
      const res = await request.post<IAxsRes<UserType>>('/login/social', {
        unionId: openId,
        source: 6
      })
      console.log(res)
    },
    // 绑定qq的短信验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile
        }
      })
    },
    // 绑定qq并登录
    async qqBindLogin(unionId: string, mobile: string, code: string) {
      const res = await request.post('/login/social/bind', {
        unionId,
        mobile,
        code
      })
      console.log(res)
    },
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile
        }
      })
    },

    async qqPatchLogin(data: any) {
      const res = await request.post<IAxsRes<UserType>>(
        `/login/social/${data.openId}/complement`,
        data
      )
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 用户退出
    logout() {
      this.profile = {} as UserType
      setProfile(this.profile)
      router.push('/login')
    }
  }
})
